﻿using MediatR;
using SqlSugar;
using Warehouse.Domain;
using Warehouse.ErrorCord;
using Warehouse.Write.Api.Actions.Warehouse.Command;

namespace Warehouse.Write.Api.Actions.Warehouse.CommandHandle
{
    public class DelCategoryCommandHandle : IRequestHandler<DelCategoryCommand, APIResult<WarehouseCategory>>
    {
        private readonly ISqlSugarClient db;

        public DelCategoryCommandHandle(ISqlSugarClient db)
        {
            this.db = db;
        }

        public async Task<APIResult<WarehouseCategory>> Handle(DelCategoryCommand request, CancellationToken cancellationToken)
        {
            APIResult<WarehouseCategory> result = new APIResult<WarehouseCategory>();
            var res = await db.Queryable<WarehouseCategory>().ToListAsync();
            string[] ids = request.WarehouseTypeId.Split(',');
            foreach (string id in ids)
            {
                var wh = res.Where(x => x.WarehouseTypeId.Equals(Convert.ToInt32(id))).FirstOrDefault();
                if (wh != null && wh.WarehouseTypeId != 0 && wh.ParentId != 0)
                {
                    wh.IsDel = !wh.IsDel;
                    await db.Updateable(wh).ExecuteCommandAsync();
                }
                else
                {
                    result.Code = APIEnum.Fail;
                    result.Msg = "有子集数据不能删除";
                    return await Task.FromResult(result);
                }
            }
            result.Code = APIEnum.Success;
            result.Msg = "删除成功";
            return await Task.FromResult(result);
        }
    }
}
